package com.rgs.rabbitmq.service.impl;

import com.rgs.rabbitmq.config.RabbitMQConfig;
import com.rgs.rabbitmq.service.RabbitMQService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: com-rgs-parent
 * @description:
 * @author: Mr.Ren
 * @create: 2023-01-06 10:38
 **/
@Service
public class RabbitMQServiceImpl implements RabbitMQService {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public String sendMsg(String msg) throws Exception {
        try {
            String msgId = UUID.randomUUID().toString().replace("-", "").substring(0, 32);
            String sendTime = sdf.format(new Date());
            Map<String, Object> map = new HashMap<>();
            map.put("msgId", msgId);
            map.put("sendTime", sendTime);
            map.put("msg", msg);
            //发送到某个交换机 以及指定路由规则
            rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_DIRECT_EXCHANGE, RabbitMQConfig.RABBITMQ_DEMO_DIRECT_ROUTING, map);
            System.out.println("生产者成功生产消息");
            return "ok";
        } catch (Exception e) {
            return "error";
        }
    }

    @Override
    public String sendMsgByFanout(String msg) throws Exception {
        try {
            Map<String, Object> message = generateMsg(msg);
            rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_FANOUT_EXCHANGE, "", message);
            System.out.println("生产者成功生产消息");
            return "ok";
        } catch (Exception e) {
            return "error";
        }

    }

    private Map<String, Object> generateMsg(String msg) {
        String msgId = UUID.randomUUID().toString().replace("-", "").substring(0, 32);
        String sendTime = sdf.format(new Date());
        Map<String, Object> map = new HashMap<>();
        map.put("msgId", msgId);
        map.put("sendTime", sendTime);
        map.put("msg", msg);
        return map;
    }
}
